<template>
  <div :class="['content-section', { active: isActive }]">
    <div class="smart-terminal-container">
      <div class="ssh-config-panel" v-if="!isConnected">
        <div class="config-header">
          <h3>🔌 SSH连接配置</h3>
          <p>请输入远程服务器连接信息</p>
        </div>

        <div class="config-form">
          <div class="form-row">
            <div class="form-group">
              <label>服务器地址:</label>
              <input v-model="sshConfig.host" placeholder="192.168.200.188" />
            </div>
            <div class="form-group">
              <label>端口:</label>
              <input v-model="sshConfig.port" type="number" placeholder="22" />
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label>用户名:</label>
              <input v-model="sshConfig.username" placeholder="root" />
            </div>
            <div class="form-group">
              <label>密码:</label>
              <input
                v-model="sshConfig.password"
                type="password"
                placeholder="请输入密码"
              />
            </div>
          </div>

          <div class="form-actions">
            <button
              @click="connectSSH"
              :disabled="connecting"
              class="connect-btn"
            >
              {{ connecting ? "🔄 连接中..." : "🚀 连接" }}
            </button>
            <button
              @click="testConnection"
              :disabled="connecting"
              class="test-btn"
            >
              🔍 测试连接
            </button>
          </div>
        </div>
      </div>

      <div class="terminal-interface" v-if="isConnected">
        <div class="terminal-header">
          <div class="terminal-title">
            <i class="terminal-icon">💻</i>
            <h2>智能终端</h2>
            <span class="subtitle"
              >{{ sshConfig.username }}@{{ sshConfig.host }}:{{
                sshConfig.port
              }}</span
            >
          </div>

          <div class="terminal-controls">
            <div class="connection-status connected">
              <span class="status-dot"></span>
              已连接
            </div>
            <button @click="disconnectSSH" class="disconnect-btn">
              断开连接
            </button>
          </div>
        </div>

        <div class="terminal-body" ref="terminalContainer">
          <div class="terminal-output" ref="outputContainer">
            <pre class="terminal-content">{{ terminalOutput }}</pre>
            <div class="terminal-cursor" :class="{ blink: showCursor }">_</div>
          </div>
        </div>
        <div v-if="showAiConfirm" class="ai-confirm-overlay">
          <div class="ai-confirm-dialog">
            <div class="ai-confirm-header">
              <h3>🤖 AI 建议确认</h3>
              <button @click="closeAiConfirm" class="close-btn">×</button>
            </div>

            <div class="ai-confirm-content">
              <div class="original-input">
                <label>您的输入：</label>
                <div class="input-text">{{ aiSuggestion?.original }}</div>
              </div>

              <div class="ai-suggestion">
                <label>AI 建议的命令：</label>
                <div
                  class="command-text"
                  contenteditable="true"
                  @input="aiSuggestion.command = $event.target.innerText"
                  v-text="aiSuggestion?.command"
                ></div>
              </div>

              <div class="ai-description" v-if="aiSuggestion?.description">
                <label>说明：</label>
                <div class="description-text">
                  {{ aiSuggestion.description }}
                </div>
              </div>
            </div>

            <div class="ai-confirm-actions">
              <button @click="acceptAiSuggestion" class="accept-btn">
                ✅ 接受并执行
              </button>
              <button @click="rejectAiSuggestion" class="reject-btn">
                ❌ 拒绝，执行原始输入
              </button>
            </div>
          </div>
        </div>

        <div class="terminal-input-area">
          <div class="input-controls">
            <div class="mode-switch">
              <button
                :class="['mode-btn', { active: intelligentMode }]"
                @click="intelligentMode = true"
              >
                🤖 智能模式
              </button>
              <button
                :class="['mode-btn', { active: !intelligentMode }]"
                @click="intelligentMode = false"
              >
                💻 直接模式
              </button>
            </div>
          </div>

          <div class="input-container">
            <div class="input-wrapper">
              <span class="command-prefix">$</span>
              <input
                v-model="currentInput"
                :placeholder="
                  intelligentMode ? '描述你想要执行的操作...' : '输入命令...'
                "
                @keyup.enter="sendCommand"
                @keyup.up="navigateHistory(-1)"
                @keyup.down="navigateHistory(1)"
                class="command-input"
                autocomplete="off"
                ref="commandInput"
                :disabled="aiAnalyzing"
              />
            </div>

            <button
              @click="sendCommand"
              :disabled="!currentInput.trim() || aiAnalyzing"
              class="send-btn"
            >
              {{ aiAnalyzing ? "🤖 AI分析中..." : "发送" }}
            </button>
          </div>

          <div class="quick-commands">
            <button
              v-for="quick in quickCommands"
              :key="quick.command"
              @click="setQuickCommand(quick)"
              class="quick-cmd-btn"
              :title="quick.description"
            >
              {{ quick.label }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, nextTick } from "vue";

export default {
  name: "SmartTerminalSection",
  props: {
    isActive: {
      type: Boolean,
      default: false,
    },
  },
  setup() {
    // SSH连接配置
    const sshConfig = ref({
      host: "192.168.137.1", // <--- 暂时写死
      port: 2201, // <--- 暂时写死
      username: "root", // <--- 暂时写死
      password: "040809Rui", // <--- 暂时写死
    });

    // 连接状态
    const isConnected = ref(false);
    const connecting = ref(false);

    // 新增：存储后端返回的SSH会话ID
    const currentSshSessionId = ref(null); // 或者初始化为空字符串

    // 终端状态
    const terminalOutput = ref("");
    const currentInput = ref("");
    const intelligentMode = ref(true);
    const showCursor = ref(true);
    const commandHistory = ref([]);
    const historyIndex = ref(-1);

    // 新增AI确认相关状态
    const aiSuggestion = ref(null); // AI建议的命令
    const showAiConfirm = ref(false); // 是否显示AI确认对话框
    const aiAnalyzing = ref(false); // AI分析中状态

    // WebSocket连接
    let websocket = null;

    // 快捷命令
    const quickCommands = ref([]);

    // 加载快捷命令
    const loadQuickCommands = async () => {
      try {
        const response = await fetch(
          "http://localhost:3210/api/terminal/quick-commands"
        );
        const commands = await response.json();
        quickCommands.value = commands;
      } catch (error) {
        console.error("加载快捷命令失败:", error);
        // 使用默认快捷命令
        quickCommands.value = [
          {
            label: "kubectl get pods",
            command: "kubectl get pods",
            description: "查看Pod",
          },
          {
            label: "kubectl get nodes",
            command: "kubectl get nodes",
            description: "查看节点",
          },
          {
            label: "kubectl get svc",
            command: "kubectl get svc",
            description: "查看服务",
          },
          { label: "clear", command: "clear", description: "清屏" },
        ];
      }
    };

    // 连接SSH
    const connectSSH = async () => {
      if (
        !sshConfig.value.host ||
        !sshConfig.value.username ||
        !sshConfig.value.password
      ) {
        alert("请填写完整的连接信息");
        return;
      }

      connecting.value = true;

      try {
        websocket = new WebSocket("ws://localhost:3210/ws/terminal");

        websocket.onopen = () => {
          console.log("WebSocket连接已建立");

          // 启动前端心跳
          setInterval(() => {
            if (websocket && websocket.readyState === WebSocket.OPEN) {
              websocket.send(
                JSON.stringify({ type: "ping", timestamp: Date.now() })
              );
            }
          }, 25000); // 每25秒发送一次心跳

          // 发送SSH连接请求
          websocket.send(
            JSON.stringify({
              type: "connect",
              config: {
                host: sshConfig.value.host,
                port: sshConfig.value.port,
                username: sshConfig.value.username,
                password: sshConfig.value.password,
              },
            })
          );
        };

        websocket.onmessage = (event) => {
          try {
            const message = JSON.parse(event.data);

            if (message.type === "connected") {
              isConnected.value = true;
              connecting.value = false;
              terminalOutput.value += `✅ ${message.message}\n`;
              // ！！！重要：保存后端返回的sessionId
              if (message.sessionId) {
                currentSshSessionId.value = message.sessionId;
                console.log("SSH会话ID:", currentSshSessionId.value);
              }

              nextTick(() => {
                const input = document.querySelector(".command-input");
                if (input) input.focus();
              });
            } else if (message.type === "error") {
              connecting.value = false;
              alert(`连接失败: ${message.message}`);
              // 连接失败时清空sessionId
              currentSshSessionId.value = null;
            } else if (message.type === "pong") {
              // 假设后端会发pong消息，这里可以处理或忽略，不显示到终端
              console.log("收到pong:", message.timestamp);
            }
            // ... (其他消息类型处理，例如 "output", "prompt" 等，保持不变) ...
          } catch (e) {
            // 普通的终端输出
            terminalOutput.value += event.data;
            scrollToBottom();
          }
        };

        websocket.onclose = () => {
          console.log("WebSocket连接已关闭");
          isConnected.value = false;
          connecting.value = false;
          currentSshSessionId.value = null; // ！！！连接关闭时清空sessionId
          alert("SSH连接已断开");
        };

        websocket.onerror = (error) => {
          console.error("WebSocket错误:", error);
          connecting.value = false;
          currentSshSessionId.value = null; // ！！！错误时清空sessionId
          alert("连接失败，请检查网络");
        };
      } catch (error) {
        connecting.value = false;
        console.error("连接失败:", error);
        alert("连接失败: " + error.message);
      }
    };

    // 断开SSH连接
    const disconnectSSH = () => {
      if (websocket) {
        websocket.send(JSON.stringify({ type: "disconnect" }));
        websocket.close();
      }
      isConnected.value = false;
      terminalOutput.value = ""; // 清空终端输出
    };

    // 发送命令
    const sendCommand = async () => {
      if (!currentInput.value.trim() || !websocket) return;

      const command = currentInput.value.trim();

      // 添加到历史记录
      commandHistory.value.unshift(command);
      if (commandHistory.value.length > 50) {
        commandHistory.value = commandHistory.value.slice(0, 50);
      }
      historyIndex.value = -1;

      if (intelligentMode.value) {
        // 智能模式：先解析命令，等待用户确认
        await requestAiAnalysis(command);
      } else {
        // 直接模式：直接发送
        sendDirectCommand(command);
        currentInput.value = "";
      }
    };

    // 请求AI分析
    const requestAiAnalysis = async (input) => {
      try {
        aiAnalyzing.value = true;

        // 显示用户输入
        terminalOutput.value += `👤 ${input}\n`;
        scrollToBottom();

        // 调用后端AI解析
        const response = await fetch(
          "http://localhost:3210/api/terminal/parse-command",
          {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              input: input,
              cluster: "ssh", // 这里的cluster和namespace需要根据实际应用逻辑获取
              namespace: "default",
            }),
          }
        );

        const result = await response.json();

        if (result.success) {
          // 显示AI分析结果，并等待用户确认
          terminalOutput.value += `🤖 AI解析: ${result.command}\n`;
          terminalOutput.value += `💡 建议执行上述命令，请确认...\n`;
          scrollToBottom();

          // 设置AI建议并显示确认对话框
          aiSuggestion.value = {
            original: input,
            command: result.command,
            description: result.description || "执行AI建议的命令",
          };
          showAiConfirm.value = true;
        } else {
          terminalOutput.value += `❌ AI解析失败: ${result.message}\n`;
          terminalOutput.value += `💡 请检查输入或切换到直接模式\n`;
          scrollToBottom();

          // 不再自动执行原始命令
          currentInput.value = ""; // 只清空输入框
        }
      } catch (error) {
        terminalOutput.value += `❌ AI解析失败: ${error.message}\n`;
        terminalOutput.value += `❓ 是否仍要执行原始命令？\n`;
        scrollToBottom();

        // 显示一个简单的确认对话框
        if (confirm("AI分析失败，是否仍要执行原始命令？")) {
          sendDirectCommand(input);
        }
        currentInput.value = "";
      } finally {
        aiAnalyzing.value = false;
      }
    };

    // 接受AI建议
    const acceptAiSuggestion = () => {
      if (aiSuggestion.value) {
        // 将AI建议的命令直接发送到SSH终端
        terminalOutput.value += `✅ 已接受AI建议，立即执行: ${aiSuggestion.value.command}\n`;
        sendDirectCommand(aiSuggestion.value.command);
        currentInput.value = ""; // 清空输入框
        scrollToBottom();
      }
      // 关闭确认对话框
      closeAiConfirm();
    };

    // 拒绝AI建议
    const rejectAiSuggestion = () => {
      if (aiSuggestion.value) {
        // 显示拒绝信息，并执行原始命令
        terminalOutput.value += `❌ 已拒绝AI建议，立即执行原始命令: ${aiSuggestion.value.original}\n`;
        sendDirectCommand(aiSuggestion.value.original);
        currentInput.value = ""; // 清空输入框
        scrollToBottom();
      }
      // 关闭确认对话框
      closeAiConfirm();
    };

    // 关闭AI确认对话框
    const closeAiConfirm = () => {
      showAiConfirm.value = false;
      aiSuggestion.value = null;
    };

    // 发送直接命令
    const sendDirectCommand = (command) => {
      if (websocket && websocket.readyState === WebSocket.OPEN) {
        // 显示要执行的命令
        terminalOutput.value += `$ ${command}\n`;
        scrollToBottom();

        // 发送命令到SSH终端
        websocket.send(
          JSON.stringify({
            type: "command",
            data: command + "\n", // 确保命令以换行符结束以便执行
          })
        );
      }
    };

    // 历史命令导航
    const navigateHistory = (direction) => {
      if (commandHistory.value.length === 0) return;

      historyIndex.value += direction;

      if (historyIndex.value < 0) {
        historyIndex.value = -1;
        currentInput.value = "";
      } else if (historyIndex.value >= commandHistory.value.length) {
        historyIndex.value = commandHistory.value.length - 1;
      }

      if (historyIndex.value >= 0) {
        currentInput.value = commandHistory.value[historyIndex.value];
      }
    };

    // 设置快捷命令
    const setQuickCommand = (quick) => {
      currentInput.value = quick.command;

      // 自动聚焦到输入框
      nextTick(() => {
        const input = document.querySelector(".command-input");
        if (input) {
          input.focus();
          input.setSelectionRange(input.value.length, input.value.length);
        }
      });
    };

    // 测试连接
    const testConnection = async () => {
      if (!sshConfig.value.host) {
        alert("请输入服务器地址");
        return;
      }

      if (!sshConfig.value.username || !sshConfig.value.password) {
        alert("请输入用户名和密码");
        return;
      }

      try {
        connecting.value = true;

        // 调用后端API测试SSH连接
        const response = await fetch(
          "http://localhost:3210/api/terminal/ssh/test-connection",
          {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              host: sshConfig.value.host,
              port: sshConfig.value.port,
              username: sshConfig.value.username,
              password: sshConfig.value.password,
            }),
          }
        );

        const result = await response.json();

        if (result.success) {
          alert(
            "✅ 连接测试成功！\n" +
              `服务器: ${result.host}:${result.port}\n` +
              `用户: ${result.username}`
          );
        } else {
          alert("❌ 连接测试失败:\n" + result.message);
        }
      } catch (error) {
        console.error("连接测试失败:", error);
        alert("❌ 连接测试失败:\n" + error.message);
      } finally {
        connecting.value = false;
      }
    };

    // 滚动到底部
    const scrollToBottom = () => {
      nextTick(() => {
        const container = document.querySelector(".terminal-output");
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    };

    // 光标闪烁
    const startCursorBlink = () => {
      setInterval(() => {
        showCursor.value = !showCursor.value;
      }, 500);
    };

    // 检查连接状态
    // 定义一个变量来存储setInterval的ID，用于后续清理
    let checkStatusInterval = null;

    // 检查连接状态
    const checkConnectionStatus = async () => {
      // 只有当 isConnected 为 true 且 currentSshSessionId 存在时才进行检查
      if (!isConnected.value || !currentSshSessionId.value) {
        console.log("不满足检查连接状态条件，跳过检查或已断开，会话ID无效。");
        // 如果连接已断开或会话ID无效，且之前有定时器在运行，则清理它
        if (!isConnected.value && checkStatusInterval) {
          clearInterval(checkStatusInterval);
          checkStatusInterval = null;
        }
        return;
      }

      try {
        const response = await fetch(
          `http://localhost:3210/api/terminal/ssh/connection-status/${currentSshSessionId.value}`
        );
        const result = await response.json();

        if (!result.connected) {
          console.log("后端报告SSH连接已断开，或sessionId已失效。");
          // 如果后端报告断开，主动调用disconnectSSH来统一处理前端的断开逻辑
          disconnectSSH();
        }
      } catch (error) {
        console.error("检查连接状态失败:", error);
        // 如果API调用本身失败（如网络错误），也视为连接异常，主动断开
        disconnectSSH();
      }
    };

    // 组件挂载
    onMounted(async () => {
      startCursorBlink();
      await loadQuickCommands();

      // 定期检查连接状态，并将定时器ID保存到 checkStatusInterval 变量中
      checkStatusInterval = setInterval(checkConnectionStatus, 30000); // 每30秒检查一次
    });

    // 组件卸载
    onUnmounted(() => {
      if (websocket) {
        // 使用原始 websocket 变量
        websocket.send(JSON.stringify({ type: "disconnect" })); // 在关闭前发送断开请求
        websocket.close();
      }
      // ！！！重要：清理定时器，避免内存泄漏和重复检查
      if (checkStatusInterval) {
        clearInterval(checkStatusInterval);
        checkStatusInterval = null; // 清理后设为null
      }
    });

    return {
      sshConfig,
      isConnected,
      connecting,
      terminalOutput,
      currentInput,
      intelligentMode,
      showCursor,
      quickCommands,
      connectSSH,
      disconnectSSH,
      sendCommand,
      navigateHistory,
      setQuickCommand,
      testConnection,
      aiSuggestion,
      showAiConfirm,
      aiAnalyzing,
      acceptAiSuggestion,
      rejectAiSuggestion,
      closeAiConfirm,
    };
  },
};
</script>

<style scoped>
.smart-terminal-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #1e1e1e;
  color: #ffffff;
  font-family: "Consolas", "Monaco", "Courier New", monospace;
}

/* SSH配置面板样式 */
.ssh-config-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40px;
}

.config-header {
  text-align: center;
  margin-bottom: 40px;
}

.config-header h3 {
  color: #00d9ff;
  font-size: 24px;
  margin-bottom: 10px;
}

.config-header p {
  color: #888;
  font-size: 16px;
}

.config-form {
  background: #2d2d2d;
  padding: 30px;
  border-radius: 12px;
  border: 1px solid #404040;
  min-width: 400px;
  max-width: 500px;
  width: 100%;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.form-group {
  flex: 1;
}

.form-group label {
  display: block;
  color: #ccc;
  margin-bottom: 8px;
  font-size: 14px;
}

.form-group input {
  width: 100%;
  background: #404040;
  color: white;
  border: 1px solid #555;
  border-radius: 6px;
  padding: 12px;
  font-size: 14px;
  font-family: inherit;
  box-sizing: border-box;
}

.form-group input:focus {
  outline: none;
  border-color: #00d9ff;
  box-shadow: 0 0 0 2px rgba(0, 217, 255, 0.2);
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin-top: 30px;
}

.connect-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s;
  min-width: 120px;
}

.connect-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
  transform: translateY(-1px);
}

.connect-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.test-btn {
  background: #404040;
  color: white;
  border: 1px solid #555;
  padding: 12px 24px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s;
  min-width: 120px;
}

.test-btn:hover:not(:disabled) {
  background: #555;
  border-color: #666;
  transform: translateY(-1px);
}

.test-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

/* 终端界面样式 */
.terminal-interface {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.terminal-header {
  background: #2d2d2d;
  padding: 20px;
  border-bottom: 1px solid #404040;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.terminal-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.terminal-icon {
  font-size: 24px;
}

.terminal-title h2 {
  margin: 0;
  color: #00d9ff;
  font-size: 20px;
}

.subtitle {
  color: #888;
  font-size: 14px;
}

.terminal-controls {
  display: flex;
  align-items: center;
  gap: 15px;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  padding: 6px 12px;
  border-radius: 12px;
  background: #333;
}

.connection-status.connected {
  background: rgba(82, 196, 26, 0.2);
  color: #52c41a;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #52c41a;
  animation: pulse 2s infinite;
}

.disconnect-btn {
  background: #f44336;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.disconnect-btn:hover {
  background: #d32f2f;
}

.terminal-body {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.terminal-output {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  font-size: 14px;
  line-height: 1.4;
  position: relative;
}

.terminal-content {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-word;
  color: #e0e0e0;
  font-family: inherit;
}

.terminal-cursor {
  display: inline-block;
  background: #00d9ff;
  width: 8px;
  height: 16px;
  margin-left: 2px;
}

.terminal-cursor.blink {
  animation: blink 1s infinite;
}

@keyframes blink {
  0%,
  50% {
    opacity: 1;
  }
  51%,
  100% {
    opacity: 0;
  }
}

.terminal-input-area {
  background: #2d2d2d;
  border-top: 1px solid #404040;
  padding: 20px;
}

.input-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.mode-switch {
  display: flex;
  background: #404040;
  border-radius: 6px;
  overflow: hidden;
}

.mode-btn {
  background: transparent;
  border: none;
  color: #ccc;
  padding: 8px 16px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.mode-btn.active {
  background: #00d9ff;
  color: #1e1e1e;
}

.input-container {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
}

.input-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  background: #404040;
  border-radius: 6px;
  padding: 0 12px;
}

.command-prefix {
  color: #00d9ff;
  margin-right: 8px;
  font-weight: bold;
}

.command-input {
  flex: 1;
  background: transparent;
  border: none;
  color: white;
  padding: 12px 0;
  font-size: 14px;
  outline: none;
  font-family: inherit;
}

.command-input::placeholder {
  color: #888;
}

.send-btn {
  background: #00d9ff;
  color: #1e1e1e;
  border: none;
  padding: 12px 24px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
  transition: all 0.3s;
  white-space: nowrap;
}

.send-btn:hover:not(:disabled) {
  background: #00b8cc;
}

.send-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.quick-commands {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.quick-cmd-btn {
  background: #333;
  color: #ccc;
  border: 1px solid #555;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s;
}

.quick-cmd-btn:hover {
  background: #404040;
  color: white;
  border-color: #666;
}

/* 滚动条样式 */
.terminal-output::-webkit-scrollbar {
  width: 6px;
}

.terminal-output::-webkit-scrollbar-track {
  background: #2d2d2d;
}

.terminal-output::-webkit-scrollbar-thumb {
  background: #555;
  border-radius: 3px;
}

.terminal-output::-webkit-scrollbar-thumb:hover {
  background: #666;
}

@keyframes pulse {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

/* AI确认对话框样式 */
.ai-confirm-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.ai-confirm-dialog {
  background: #2d2d2d;
  border-radius: 12px;
  border: 1px solid #404040;
  min-width: 500px;
  max-width: 700px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
}

.ai-confirm-header {
  padding: 20px;
  border-bottom: 1px solid #404040;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ai-confirm-header h3 {
  margin: 0;
  color: #00d9ff;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  color: #888;
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.3s;
}

.close-btn:hover {
  background: #404040;
  color: white;
}

.ai-confirm-content {
  padding: 20px;
}

.original-input,
.ai-suggestion,
.ai-description {
  margin-bottom: 16px;
}

.original-input label,
.ai-suggestion label,
.ai-description label {
  display: block;
  color: #ccc;
  font-size: 14px;
  margin-bottom: 8px;
  font-weight: bold;
}

.input-text {
  background: #404040;
  color: #e0e0e0;
  padding: 12px;
  border-radius: 6px;
  border-left: 4px solid #00d9ff;
  font-family: "Consolas", "Monaco", "Courier New", monospace;
  font-size: 14px;
  line-height: 1.5;
  min-height: 2.5em; /* 确保最小高度 */
  word-break: break-all; /* 防止长文本溢出 */
  white-space: pre-wrap; /* 保留空白符和换行 */
}

.command-text {
  /* 调整样式使其与 .input-text 和 .description-text 视觉一致 */
  background: #1a4b1a; /* 与原 AI 建议命令的背景色一致 */
  color: #90ee90; /* 与原 AI 建议命令的文字颜色一致 */
  padding: 12px;
  border-radius: 6px;
  border-left: 4px solid #4caf50; /* 与原 AI 建议命令的左侧边框一致 */
  font-family: "Consolas", "Monaco", "Courier New", monospace;
  font-weight: bold; /* 保持加粗 */
  font-size: 14px;
  line-height: 1.5;
  outline: none; /* 移除聚焦时的默认边框 */
  min-height: 2.5em; /* 确保最小高度，使其与 input-text 等高 */
  word-break: break-all; /* 防止长文本溢出 */
  white-space: pre-wrap; /* 保留空白符和换行 */
}

.command-text:focus {
  border-color: #00d9ff; /* 聚焦时边框颜色变化 */
  box-shadow: 0 0 0 2px rgba(0, 217, 255, 0.2);
}

.description-text {
  background: #404040;
  color: #ffd700;
  padding: 12px;
  border-radius: 6px;
  border-left: 4px solid #ff9800;
  font-family: inherit;
  font-size: 14px;
  line-height: 1.5;
  min-height: 2.5em; /* 确保最小高度 */
  word-break: break-all; /* 防止长文本溢出 */
  white-space: pre-wrap; /* 保留空白符和换行 */
}

.ai-confirm-actions {
  padding: 20px;
  border-top: 1px solid #404040;
  display: flex;
  gap: 12px;
  justify-content: center;
}

.accept-btn {
  background: linear-gradient(135deg, #4caf50 0%, #45a049 100%);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
  transition: all 0.3s;
  min-width: 180px;
}

.accept-btn:hover {
  background: linear-gradient(135deg, #45a049 0%, #3d8b40 100%);
  transform: translateY(-1px);
}

.reject-btn {
  background: linear-gradient(135deg, #f44336 0%, #d32f2f 100%);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
  transition: all 0.3s;
  min-width: 180px;
}

.reject-btn:hover {
  background: linear-gradient(135deg, #d32f2f 0%, #b71c1c 100%);
  transform: translateY(-1px);
}

/* AI分析中状态 */
.command-input:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.send-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ai-confirm-dialog {
    min-width: auto;
    margin: 20px;
    max-width: none;
  }

  .ai-confirm-actions {
    flex-direction: column;
  }

  .accept-btn,
  .reject-btn {
    width: 100%;
    min-width: auto;
  }
}
</style>
